package solution19;

/**
 * 【快慢指针】
 * 删除链表倒数第n个结点
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        // Advances first pointer so that the gap between first and second is n nodes apart
        // first先指向第n+1个结点，结点从1开始
        // 就是让first指针先走n+1步，这样两个指针之间就有n个结点
        // 当first指向null的时候，second指针指向倒数n+1个结点
        // 这样，second.next=second.next.next就可以把倒数第n个结点删除
        for (int i = 1; i <= n + 1; i++) {
            first = first.next;
        }
        // Move first to the end, maintaining the gap
        // 让second指向要删除的结点之前的那个结点，也就是让first结点指向null
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        // 删除第n个结点
        second.next = second.next.next;
        return dummy.next;
    }
}


